package com.jack.helloworld.fragment.lifecycle;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.jack.helloworld.R;
import com.orhanobut.logger.Logger;

public class FragmentActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnFragmentLeft;
    private Fragment rightFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        init();
    }


    private void init() {
        btnFragmentLeft = (Button) findViewById(R.id.btn_fragment_left);
        btnFragmentLeft.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_fragment_left:
                try {
                    AnotherRightFragment anotherRightFragment = new AnotherRightFragment();
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    if (rightFragment == null) {
                        rightFragment = getFragmentManager().findFragmentById(R.id.right_fragment);
                        Logger.d("onClick#rightFragment: " + rightFragment);
                    }

                    //fragmentTransaction.replace(R.id.right_fragment, anotherRightFragment);
                    if (rightFragment != null) {
                        fragmentTransaction.remove(rightFragment);
                    }
                    fragmentTransaction.add(R.id.right_layout, anotherRightFragment);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                } catch (Exception e) {
                    Logger.e(e, "onClick#ERR: " + e.getMessage());
                }
                break;
        }
    }
}
